<div class="share-embed" class:pending>
    <h2>{@html __('publish / share-embed') }</h2>
    <div class="share-embed-block">
        <IconDisplay size="30px" icon="link" color="#333333" class="pt-5 pr-5" />
        <div class="share-embed-item">
            <label for="share-url">{@html __('publish / share-url') }</label>
            <div class="copy-group">
                <div class="copy-preview share-url">
                    <input
                        ref:shareurl
                        type="text"
                        id="share-url"
                        class="passive-input"
                        value="{shareUrl}"
                        readonly
                    />
                    <a target="_blank" class="share-url-link" href="{shareUrl}"> </a>
                </div>
                <button
                    class="btn copy-button"
                    on:click="copy('shareurl')"
                    title="{ __('publish / copy') }"
                >
                    <IconDisplay size="18px" icon="copy-to-clipboard" class="pt-1" />
                </button>
                <span class="copy-success" class:show="copySuccess.shareurl">
                    { __('publish / copy-success') }
                </span>
            </div>
            <RadioControl options="{shareOptions}" bind:value="shareurlType" label="" />
        </div>
    </div>

    <div class="share-embed-block">
        <IconDisplay
            size="30px"
            icon="source-code"
            color="#333333"
            class="pt-5 pr-5"
            valign="bottom"
        />
        <div class="share-embed-item">
            <label for="embed-code">{@html __('publish / embed') }</label>
            <div class="copy-group">
                <div class="copy-preview embed-code">
                    <input
                        ref:embedcode
                        type="text"
                        class="passive-input"
                        value="{embedCode}"
                        id="embed-code"
                        readonly
                        on:click="this.select()"
                    />
                </div>
                <button
                    class="btn copy-button"
                    on:click="copy('embedcode')"
                    title="{ __('publish / copy') }"
                >
                    <IconDisplay size="18px" icon="copy-to-clipboard" class="pt-1" />
                </button>
                <span class="copy-success" class:show="copySuccess.embedcode">
                    { __('publish / copy-success') }
                </span>
            </div>

            <RadioControl options="{embedOptions}" bind:value="embedType" label="" />

            <p class="embed-explanation">{@html __('publish / embed / explanation') }</p>
        </div>
    </div>
</div>

<style>
    label {
        display: inline-block;
        font-weight: normal;
    }

    .share-embed {
        margin: 30px 0;
    }

    .share-embed.pending {
        opacity: 0.5;
        pointer-events: none;
    }

    .share-embed-block {
        display: flex;
        position: relative;
    }

    .share-embed-block:first-of-type {
        margin-bottom: 12px;
        border-bottom: 1px solid #ddd;
    }

    .share-embed-item {
        flex: 1;
    }

    .copy-success {
        font-size: 12px;
        color: #39a832;
        opacity: 0;
        pointer-events: none;
        position: absolute;
        top: 0;
        right: 0;
        transition: opacity 300ms;
    }

    .copy-success.show {
        transition: none;
        opacity: 1;
    }

    .copy-group {
        display: flex;
        padding: 6px 0;
    }

    .copy-preview {
        position: relative;
        flex: 1;
        background: #f5f5f5;
        border: 1px solid #dddddd;
        border-radius: 4px;
        overflow: hidden;
    }

    .copy-button {
        flex: 0 0 40px;
        margin-left: 5px;
        padding: 0;
    }

    /* Preview holder for copying to clipboard */
    .passive-input {
        margin: 0;
        width: calc(100% - 15px);
        overflow: hidden;
        background: transparent;
        border: none;
        text-overflow: ellipsis;
        white-space: nowrap;
        display: inline-block;
        cursor: text;
    }

    .passive-input::selection {
        background: #dadada;
    }

    .embed-code .passive-input {
        color: #4f4f4f;
        font-size: 12px;
    }

    /* Faux link styling for input */
    .share-url .passive-input {
        color: #1d81a2;
        font-size: 16px;
        font-weight: 500;
        padding-bottom: 0;
    }

    /* Faux link hover styling for input */
    .share-url:hover .passive-input {
        text-decoration: underline;
        color: #15607a;
    }

    /* Invisible link element for share URL */
    .share-url-link {
        position: absolute;
        top: 0;
        right: 0;
        bottom: 0;
        left: 0;
        outline: none;
    }

    .embed-explanation {
        font-size: 12px;
        color: #848484;
    }

    .embed-explanation :global(a) {
        font-weight: bold;
    }
</style>

<script>
    import IconDisplay from '@datawrapper/controls/IconDisplay.html';
    import RadioControl from '@datawrapper/controls/RadioControl.html';
    import { __ } from '@datawrapper/shared/l10n';
    import { trackEvent } from '@datawrapper/shared/analytics';
    import get from '@datawrapper/shared/get';
    import purifyHtml from '@datawrapper/shared/purifyHtml';

    export default {
        components: {
            IconDisplay,
            RadioControl
        },
        data() {
            return {
                embedTemplates: [],
                pluginShareurls: [],
                pending: false,
                shareurlType: 'default',
                embedType: 'responsive',
                copySuccess: {}
            };
        },
        computed: {
            shareUrl({ shareurlType, id, publicUrl, metadata, pluginShareurls }) {
                if (shareurlType === 'default') return publicUrl;
                let url = '';

                pluginShareurls.forEach(t => {
                    if (t.id === shareurlType) {
                        url = t.url.replace(/%chart_id%/g, id);

                        url = url.replace(/%(.*?)%/g, (match, path) => {
                            return get({ id, metadata }, path);
                        });
                    }
                });
                return url;
            },
            embedCode({ embedType, publicUrl, metadata }) {
                if (!metadata) return '';
                if (metadata.publish && !metadata.publish['embed-codes']) {
                    return `<iframe src="${publicUrl}" width="100%" height="${metadata.publish['embed-height']}" scrolling="no" frameborder="0" allowtransparency="true"></iframe>`;
                }
                if (metadata.publish['embed-codes']['embed-method-' + embedType]) {
                    return metadata.publish['embed-codes']['embed-method-' + embedType];
                } else {
                    return '';
                }
            },
            shareOptions({ pluginShareurls }) {
                const defaultOption = {
                    label: __('publish / share-url / fullscreen'),
                    value: 'default',
                    help: __('publish / help / share-url / fullscreen')
                };

                const pluginShareOptions = pluginShareurls.map(({ name, id }) => ({
                    label: name,
                    value: id,
                    help: __(`publish / help / share-url / ${id}`)
                }));

                return [defaultOption, ...pluginShareOptions];
            },
            embedOptions({ embedTemplates }) {
                return embedTemplates.map(({ title, id, text }) => ({
                    label: purifyHtml(title),
                    value: purifyHtml(id),
                    help: purifyHtml(text)
                }));
            }
        },
        helpers: {
            __
        },
        methods: {
            copy(targetRef) {
                const { embedCode, shareUrl } = this.get();
                const copyText = targetRef === 'embedcode' ? embedCode : shareUrl;

                // create new element to preserve line breaks
                const el = document.createElement('textarea');
                el.value = copyText;
                document.body.appendChild(el);
                el.select();

                try {
                    const successful = document.execCommand('copy');
                    if (successful) {
                        const { copySuccess } = this.get();
                        copySuccess[targetRef] = true;
                        this.set({ copySuccess });
                        setTimeout(() => {
                            copySuccess[targetRef] = false;
                            this.set({ copySuccess });
                        }, 2000);
                        trackEvent('Chart Editor', `${targetRef}-copy`);
                    }
                } catch (err) {
                    console.error('Could not copy to clipboard.');
                }

                document.body.removeChild(el);
                /*
                    make it look like the visible input
                    is the one that's actually selected
                */
                this.refs[targetRef].select();
            }
        }
    };
</script>
